package org.tgcloud.group.web.controller.manager;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import io.swagger.annotations.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.tgcloud.group.core.APPResultMessage;
import org.tgcloud.group.core.BeanUtil;
import org.tgcloud.group.core.DateUtil;
import org.tgcloud.group.core.custom.Permissions;
import org.tgcloud.group.core.session.Session;
import org.tgcloud.group.service.manager.PayRollManageService;
import org.tgcloud.group.web.controller.dto.PayRoll.PayRollImportDTO;
import org.tgcloud.group.web.controller.req.page.PayRollSearchReq;

import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author: zhy
 * @create: 2023-10-30 09:08
 * @description: 工资相关接口
 */
@Api(tags = "工资相关接口")
@RestController
@RequestMapping("/manager/pc/user")
@EnableAutoConfiguration
public class PayRollManageController extends ManageAPPBaseController{

    @Autowired
    private PayRollManageService payRollManageService;

    @ApiOperation(value = "导入excel")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, dataType = "string")
    })
    @ResponseBody
    @RequestMapping(value = "/importExcelProjectHistoryDTO", method = RequestMethod.POST)
    public APPResultMessage doImportExcelProjectHistoryDTO(@RequestPart("file") MultipartFile file,
                                                        @ModelAttribute("session") Session session){
        return payRollManageService.doImportExcelProjectHistoryDTO(file);
    }


    @Permissions("payRoll:add")
    @ApiOperation(value = "导入工资单excel")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, dataType = "string")
    })
    @ResponseBody
    @RequestMapping(value = "/importExcelPayRoll", method = RequestMethod.POST)
    public APPResultMessage doImportExcelPayRoll(@RequestPart("file") MultipartFile file,
                                                 @RequestParam Long time,
                                                 @ModelAttribute("session") Session session){
        return payRollManageService.doImportExcelPayRoll(file, time == null ? null : new Date(time));
    }


    @Permissions("payRoll:view")
    @ApiOperation(value = "工资表列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, dataType = "string"),
    })
    @ResponseBody
    @RequestMapping(value = "/getPayRollList", method = RequestMethod.POST)
    public APPResultMessage getPayRollList(@ModelAttribute("session") Session session,
                                                         @RequestBody PayRollSearchReq req) {
        return payRollManageService.getPayRollList(req.getPageNum(),req.getPageSize(),req.getTime() == null ? null : new Date(req.getTime()));
    }


    @Permissions("payRoll:view")
    @ApiOperation(value = "工资表当月列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, dataType = "string"),
    })
    @ResponseBody
    @RequestMapping(value = "/getPayRollMonthList", method = RequestMethod.POST)
    public APPResultMessage getPayRollMonthList(@ModelAttribute("session") Session session,
                                           @RequestBody PayRollSearchReq req) {
        return payRollManageService.getPayRollMonthList(req.getPageNum(),req.getPageSize(),req.getTime() == null ? null : new Date(req.getTime()),
                req.getUserType(), req.getUserTypeName());
    }



    /* 导出 */
    @ApiOperation(value = "导出工资表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, dataType = "string"),
    })
    @ResponseBody
    @PostMapping(value = "/doExportPayRoll")
    public void doExportPayRoll(HttpServletResponse response,
                              @RequestParam Long time) throws Exception {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/octet-stream;charset=UTF-8");
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMM");
        SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyyMMddHHmm");
        String excelName = dateFormat.format(new Date(time)) + "工资表" + dateFormat1.format(new Date());
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(excelName, "UTF-8") + ".xls");
        response.addHeader("filename", URLEncoder.encode(excelName, "UTF-8"));

        // 获取excel显示第一行的字段名
        List<String> headers = Lists.newArrayList();
        PayRollImportDTO msg = new PayRollImportDTO();
        Field[] declaredFields = msg.getClass().getDeclaredFields();
        for (Field field : declaredFields){
            field.setAccessible(true);
            String value = field.getAnnotation(ApiModelProperty.class).value();
            headers.add(value);
        }

        try {
            OutputStream out = response.getOutputStream();
            APPResultMessage successMessage = payRollManageService.getPayRollMonthExportList(time == null ? null : new Date(time));
            getExportPayRollListExcel(excelName, headers, successMessage, out);
            out.close();
            System.out.println("excel导出成功！");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void getExportPayRollListExcel(String title, List<String> headers, APPResultMessage message, OutputStream out) throws Exception{
        //声明一个工作簿
        HSSFWorkbook workbook = new HSSFWorkbook();
        //生成一个表格
        HSSFSheet sheet = workbook.createSheet(title);
        //设置表格默认列宽度为15个字符
        sheet.setDefaultColumnWidth(20);
        //生成一个样式，用来设置标题样式
        HSSFCellStyle style = workbook.createCellStyle();
        //设置这些样式
        style.setFillForegroundColor(HSSFColor.HSSFColorPredefined.SKY_BLUE.getIndex());
        //生成一个字体
        HSSFFont font = workbook.createFont();
        font.setColor(HSSFColor.HSSFColorPredefined.VIOLET.getIndex());
        //把字体应用到当前的样式
        style.setFont(font);
        // 生成并设置另一个样式,用于设置内容样式
        HSSFCellStyle style2 = workbook.createCellStyle();
        style2.setFillForegroundColor(HSSFColor.HSSFColorPredefined.LIGHT_YELLOW.getIndex());
        // 生成另一个字体
        HSSFFont font2 = workbook.createFont();
        // 把字体应用到当前的样式
        style2.setFont(font2);
        //产生表格标题行
        HSSFRow row = sheet.createRow(0);
        for (int i = 0; i < headers.size(); i++) {
            HSSFCell cell = row.createCell(i);
            cell.setCellStyle(style);
            HSSFRichTextString text = new HSSFRichTextString(headers.get(i));
            cell.setCellValue(text);
        }

        List list = message.getResult().getList();
        if (!BeanUtil.isNullList(list)) {
            for (int i = 0; i < list.size(); i++) {
                row = sheet.createRow(i + 1);
                int j = 0;
                PayRollImportDTO dto = (PayRollImportDTO) list.get(i);
                // 获取excel里对应的值
                Field[] declaredFields = dto.getClass().getDeclaredFields();
                for (Field field : declaredFields){
                    field.setAccessible(true);
                    Object o = field.get(dto);
                    HSSFCell cell = row.createCell(j++);
                    if (o == null){
                        cell.setCellValue("");
                    }else {
                        if (o instanceof BigDecimal){
                            CellStyle cellStyle = workbook.createCellStyle();
                            DataFormat dataFormat = workbook.createDataFormat();  //创建一个单元格数据格式
                            cellStyle.setDataFormat(dataFormat.getFormat("#,##0.00"));  //设置数据格式为数字
                            cell.setCellStyle(cellStyle);
                            if (JSON.toJSONString(o).equals("0E-8")){
                                cell.setCellValue(0);
                            }else if (JSON.toJSONString(o).equals("0E-24")){
                                cell.setCellValue(0);
                            }else {
                                cell.setCellValue(((BigDecimal) o).longValue());
                            }
                        }else {
                            cell.setCellValue(o.toString());
                        }
                    }
                }

            }
        }
        try {
            workbook.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @Permissions("payRoll:del")
    @ApiOperation(value = "删除工资表当月")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, dataType = "string"),
    })
    @ResponseBody
    @RequestMapping(value = "/doDelPayRollMonth", method = RequestMethod.POST)
    public APPResultMessage doDelPayRollMonth(@ModelAttribute("session") Session session,
                                              @RequestBody PayRollSearchReq req) {
        return payRollManageService.doDelPayRollMonth(req.getTime() == null ? null : new Date(req.getTime()));
    }



}
